package com.oneonefive.educationsystem.controller;

import com.oneonefive.educationsystem.domain.Student;
import com.oneonefive.educationsystem.dto.Result;
import com.oneonefive.educationsystem.service.StudentService;
import com.oneonefive.educationsystem.vo.StudentVo;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/stu")
public class StudentController {
    @Resource
    StudentService studentService;

    @PostMapping()
    @PreAuthorize("hasAuthority('admin')")
    public Result stuSave(@RequestBody Student student) {
        Result legitimacy = studentService.legitimacy(student);
        if (!legitimacy.getSuccess()) {
            return legitimacy;
        }
        return studentService.saveOne(student);
    }

    @PostMapping("/upload")
    @PreAuthorize("hasAuthority('admin')")
    public Result uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        return studentService.uploadExcel(file);
    }

    @DeleteMapping("/{studentId}")
    @PreAuthorize("hasAuthority('admin')")
    public Result stuDelete(@PathVariable Integer studentId) {
        return studentService.stuDelete(studentId);
    }

    @PutMapping()
    @PreAuthorize("hasAuthority('admin')")
    public Result stuUpdate(@RequestBody Student student) {
        Result legitimacy = studentService.legitimacy(student);
        if (!legitimacy.getSuccess()) {
            return legitimacy;
        }
        return studentService.stuUpdate(student);
    }

    //data:List<Student>
    @PostMapping("/1")
    @PreAuthorize("hasAuthority('admin')")
    public Result stuList(@RequestBody StudentVo studentVo) {
        if (studentVo.getPage() == null) {
            return Result.fail("请给出当前页数");
        }
        return studentService.stuList(studentVo);
    }

    //查出所有班级和这个班级学生数量的
    @GetMapping("/clazz")
    @PreAuthorize("hasAuthority('teacher')")
    public Result clazzList() {
        System.out.println("arrive");
        return studentService.clazzList();
    }

    @DeleteMapping("/allDelete")
    @PreAuthorize("hasAuthority('admin')")
    public Result allDelete(@RequestBody List<Integer> list) {
        for (Integer integer : list) {
            boolean b = studentService.removeById(integer);
            if (!b) {
                return Result.fail(integer + "删除失败");
            }
        }
        return Result.ok("批量删除成功");
    }

}
